from django.db import models


# Create your models here.


class User(models.Model):
    name = models.CharField(max_length=20, verbose_name='用户名')
    passwd = models.CharField(max_length=20, verbose_name='密码')
    email = models.EmailField(verbose_name='邮箱')
    is_active = models.BooleanField(default=False)

    class Meta:
        db_table = 'bw_users'


class AddressManager(models.Manager):
    def get_default(self, user_id):
        """获取用户的默认地址"""
        try:
            addr = self.get(id=user_id, is_default=True)
        except self.model.DoesNotExist:
            addr = None
        return addr

    def add_address(self, user_id, recipient, address, zip_code, phone):
        """添加地址"""
        has_default_address = self.get_default(user_id)
        is_default = True if has_default_address else False
        addr = self.create(user_id=user_id, recipient=recipient,
                           address=address,
                           zip_code=zip_code, phone=phone,
                           is_default=is_default)


class UserAddress(models.Model):
    recipient = models.CharField(max_length=20, verbose_name='收件人')
    address = models.CharField(max_length=100, verbose_name='收件地址')
    zip_code = models.CharField(max_length=6, verbose_name='邮政编码')
    phone = models.CharField(max_length=11, verbose_name='联系电话')
    is_default = models.BooleanField(default=False, verbose_name='设置为默认地址')
    owner = models.ForeignKey('User', verbose_name='所有者',
                              on_delete=models.CASCADE)

    objects = AddressManager()

    def to_dict(self):
        return {'recipient': self.recipient, 'address': self.address,
                'zip_code': self.zip_code, 'phone': self.phone}

    class Meta:
        db_table = 'bw_address'
        permissions = [
            ('modify_address', '修改地址'),
        ]